const utils = require('../../utils/util.js')
const person = wx.cloud.database().collection('person')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    contact:['手机号码','邮箱','微信','QQ'],
    figureID:[],
    figureUrl:[],
    imgnum:0,
    personalData:'',
    faculty: ['文传', '电气', '外国语', '艺创', '医管', '商学院', '护理系', '会计', '公管', '音乐系','继教'],
    major: [['网新', '汉语言', '新闻'], ['计算机', '通信工程', '电气工程', '电子信息'], ['英语', '法语', '日语', '韩语', '汉语国际'], ['艺术设计', '数媒', '公共艺术',], ['医检'], ['工商管理', '经济学', '市场营销', '国贸', '旅游管理', '物流管理', '电商', '国际商务', '房地产开发', '文化产业', '金工'], ['护理学'], ['会计学', '财务管理', '审计学'], ['行政管理', '公共关系', '人力'], ['音乐学'], ['商务英语', '法学', '动漫设计','行政工商','航空']],
    grade:['大一','大二','大三','大四','其它']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.openid = options.id
    person.where({
      _openid: options.id
    }).get()
      .then(res => {
        var data = res.data[0]
        this.data.personalData = data._id
        this.setData({
          avatar: data.avatarImage,
          nickName: data.name,
          id: data._id,
          hobby:data.hobby,
          xingge:data.xingge,
          contactInfo: data.contactInfo,
          contactType: data.contactType,
          figures:data.images,
          yuanxi:data.faculty,
          //this.setData的数据会和this.data的数据冲突，所以用major2了
          major2: res.data[0].major,
          nianji:data.grade
        })
      }) 
  },

selectType(e){
  this.setData({contactType:this.data.contact[e.detail.value]})
},

selectGrade:function(e){
  this.setData({ nianji: this.data.grade[e.detail.value] })
},

selectFaculty: function (e) {
  this.setData({ yuanxi: this.data.faculty[e.detail.value], zhuanye: this.data.major[e.detail.value]})
},

selectMajor: function (e) {
  this.setData({ mindex: e.detail.value })
},

checkContactInfo: function (type, info) {
  var phoneReg = /^1[3-578]\d{9}$/;
  var mailReg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
  var qqReg = /^\s*[.0-9]{5,11}\s*$/;
  if (type == '手机号码') {
    if (!phoneReg.test(info)) {
      // 验证输入内容为不合法
      return true
    }
    else {
      // 验证输入无误
      return false
    }
  }
  else if (type == '邮箱') {
    if (!mailReg.test(info)) {
      return true
    }
    else {
      return false
    }
  }

  else if (type == 'QQ'){
    if (!qqReg.test(info)) {
      return true
    }
    else {
      return false
    }
  }
},

  addimages: function (e) {
    // 因为在api内部，this对象的setData属性不被允许使用，所以就间接赋值给that方便传输文件路径至wxml的内部状态变量中。
    var that = this
    var img = new Array()
    var openid = wx.getStorageSync('openID')
    var time = utils.formatTime(new Date())
    wx.chooseImage({
      count: 3,
      success: function (res) {
        wx.showToast({
          title: '正努力加载图片',
          duration: 2000,
          mask: true,
          image: '/images/shenglvehao.png'
        })
        var tempFilePaths = res.tempFilePaths
        if (that.data.imgnum + tempFilePaths.length < 4) {
          // figurerurl用于渲染
          that.data.figureUrl = that.data.figureUrl.concat(tempFilePaths)
          // figurenum用于计数 新增个变量来保存图片数量，一张张上传图片都不会出错
          var figurenum = new Array()
          figurenum = figurenum.concat(tempFilePaths)
          that.data.imgnum += figurenum.length
          that.setData({ figures: that.data.figureUrl })
          for (var num = -1; num < that.data.figureUrl.length;) {
            num++
            var name = time.substring(0, 5) + '/' + openid + '_' + num + '_' + Math.floor(Math.random() * 100)
            wx.cloud.uploadFile({
              cloudPath: `${name}.png`,
              filePath: that.data.figureUrl[num],
              success: res => {
                that.data.figureID.push(res.fileID)
              },
            })
          }
        }
        else {
          wx.showModal({
            title: '提示',
            content: '上传的图片数量不能超过3张哦',
          })
        }
      }
    })
  },

  delimages: function (e) {
    // 增加调用deleteFile API节省存储空间
    wx.cloud.deleteFile({
      fileList: this.data.figureID
    })
    this.data.figureID = []
    this.data.imgnum = 0
    this.data.figureUrl = []
    this.setData({ figureID: [], figures: [] })
  },

  cancle(){
    // navigateBack 返回上级页面，不能随便设置路由了
    wx.navigateBack({
      url: `/pages/personal/personal?id=${this.data.openid}`+'&type=myself'
    })
  },

  submitForm(e){
    wx.showLoading({
      title: '正在修改……',
    })
    var req = e.detail.value
    if (this.checkContactInfo(req.contactType, req.contactInfo)){
      
      wx.showToast({
        title: '请检查联系方式',
        image: '/images/close-circle.png'
      })
    }

  // 输入了具体联系方式有没有选择联系类型的
    else if (!req.contactType && req.contactInfo){
      wx.showToast({
        title: '请选择联系方式',
        image: '/images/close-circle.png'
      })
    }

    else{
      person.doc(this.data.personalData).update({
        data: {
          name: req.nickName,
          hobby: req.hobby,
          xingge: req.xingge,
          contactType: req.contactType,
          contactInfo: req.contactInfo,
          images: this.data.figureID,
          faculty: req.faculty,
          major: req.major,
          grade: req.grade
        }
      })
      var userInfo = wx.getStorageSync('userInfo')
      var user = [req.nickName, userInfo.avatarUrl, userInfo.gender]
      wx.setStorageSync('userInfo', user)
      wx.switchTab({
        url: '/pages/me/me'
      })
    }
    
    wx.hideLoading()
  },
})